import { login, register, getUserInfo } from '@/api/user';

const state = {
  currentUser: JSON.parse(localStorage.getItem('user')) || null,
  token: localStorage.getItem('token') || '',
};

const mutations = {
  SET_USER(state, user) {
    state.currentUser = user;
    localStorage.setItem('user', JSON.stringify(user));
  },
  SET_TOKEN(state, token) {
    state.token = token;
    localStorage.setItem('token', token);
  },
  LOGOUT(state) {
    state.currentUser = null;
    state.token = '';
    localStorage.removeItem('user');
    localStorage.removeItem('token');
  }
};

const actions = {
  login({ commit }, credentials) {
    return login(credentials).then(response => {
      const { data } = response;
      const token = Math.random().toString(36).substring(7); // Mock token
      commit('SET_USER', data);
      commit('SET_TOKEN', token);
      return data;
    });
  },
  register({ commit }, userInfo) {
    return register(userInfo).then(response => {
        const { data } = response;
        const token = Math.random().toString(36).substring(7); // Mock token
        commit('SET_USER', data);
        commit('SET_TOKEN', token);
        return data;
    });
  },
  fetchUserInfo({ commit }, userId) {
    return getUserInfo(userId).then(response => {
      commit('SET_USER', response.data);
      return response.data;
    });
  },
  logout({ commit }) {
    commit('LOGOUT');
  }
};

const getters = {
  isAuthenticated: state => !!state.token,
  currentUser: state => state.currentUser,
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
}; 